package com.xiaohai.wx.weather.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import javax.xml.bind.Marshaller;

import org.apache.log4j.Logger;

public class NetworkUtil {
	
	public static Logger logger = Logger.getLogger(NetworkUtil.class.getName());
	
	public static String readURLContent(String url){
		
		try {
			URL urlObj = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
			conn.setRequestMethod("GET");
			//conn.setRequestProperty("Accept", "application/json");
	 
			/*
			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}*/
	 
			BufferedReader br;
			
			br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));
			 
	 		String tempOut;
			if ((tempOut = br.readLine()) != null) {
				return tempOut;
			}
			conn.disconnect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
		
	}
	

	 public static String doGet(String urlStr,Map<String,Object> paramMap ) throws Exception{
         String paramStr = prepareParam(paramMap);
         if(paramStr == null || paramStr.trim().length()<1){
            
         }else{
             urlStr +="?"+paramStr;
         }
         logger.debug("doGet: "+ urlStr);
         URL url = new URL(urlStr);
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
         conn.setRequestMethod("GET");
         //conn.setRequestProperty("Content-Type","text/html; charset=UTF-8");
        
         conn.connect();
         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line ;
         String result ="";
         while( (line =br.readLine()) != null ){
             result += "/n"+line;
         }
         
         if(!result.equals("")){
        	 result = result.substring(2);
         }
         logger.debug(result);
         return result;
     }
	 
	 public static String  doPost(String urlStr,Map<String,Object> paramMap ) throws Exception{
         URL url = new URL(urlStr);
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
         conn.setRequestMethod("POST");
         String paramStr = prepareParam(paramMap);
         conn.setDoInput(true);
         conn.setDoOutput(true);
         OutputStream os = conn.getOutputStream();    
         os.write(paramStr.toString().getBytes("utf-8"));    
         os.close();        
        
         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line ;
         String result ="";
         while( (line =br.readLine()) != null ){
             result += "/n"+line;
         }
        
         br.close();
         return result;
     }
	 
	 public static String  doPost(String urlStr,String content ) throws Exception{
         URL url = new URL(urlStr);
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
         conn.setRequestMethod("POST");
         conn.setDoInput(true);
         conn.setDoOutput(true);
         OutputStream os = conn.getOutputStream();    
         os.write(content.getBytes("utf-8"));    
         os.close();        
        
         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line ;
         String result ="";
         while( (line =br.readLine()) != null ){
             result += "/n"+line;
         }
        
         br.close();
         return result;
     }
	 
	 public static String  doPostXML(String urlStr,Marshaller m, Object xmlObj) throws Exception{
         URL url = new URL(urlStr);
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
         conn.setRequestMethod("POST");
         conn.setDoInput(true);
         conn.setDoOutput(true);
         OutputStream os = conn.getOutputStream(); 
         m.marshal(xmlObj, os);
         os.flush();
         //os.write(paramStr.toString().getBytes("utf-8"));    
         os.close();        
        
         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line ;
         String result ="";
         while( (line =br.readLine()) != null ){
             result += "/n"+line;
         }
        
         br.close();
         return result;
     }
	
	private static String prepareParam(Map<String,Object> paramMap){
        StringBuffer sb = new StringBuffer();
        if(paramMap.isEmpty()){
            return "" ;
        }else{
            for(String key: paramMap.keySet()){
                String value = (String)paramMap.get(key);
                if(sb.length()<1){
                    sb.append(key).append("=").append(value);
                }else{
                    sb.append("&").append(key).append("=").append(value);
                }
            }
            return sb.toString();
        }
    }

}
